import Vue from 'vue';
import Vuex from 'vuex';
import axios from "@/utils/request";
import VueObject from '@/main.ts';

Vue.use(Vuex);

const Util = {
  setLocalStorage(name: string, value: string) {
    let localName: string = "dianxiaotong-" + name;
    localStorage.setItem(localName, value);
  },
  getLocalStorage(name: string) {
    let localName: string = "dianxiaotong-" + name;
    return JSON.parse(localStorage.getItem(localName) || '{}');
  },
  removeLocalStorage(name: string) {
    let localName: string = "dianxiaotong-" + name;
    localStorage.removeItem(localName);
  },
  clearLocalStorage() {
    localStorage.clear();
  }
}

export default new Vuex.Store({
  state: {
    login: false,
    scrollTop: 0,
    userInfo: { token: '', userName: '' },
    wxSwitch: 0,
    config: {}
  },
  getters: {
    ifKefu(state) {
      return state.userInfo.userName == '牛伟' || state.userInfo.userName == '赵蓉'
    }
  },
  mutations: {
    setUserInfo(state, value) {
      state.userInfo = value;
      Util.setLocalStorage('userInfo', JSON.stringify(value));
    },
    setState(state: any, value: any) {
      for( let key in value ) { state[ key ] = value[ key ]; }
    },
    getUserInfo(state, value) {
      state.userInfo = Util.getLocalStorage('userInfo');
    },
    setscrollTop(state, value) {
      state.scrollTop = value;
    },
    exit(state, value) {
      state.userInfo = { token: '', userName: '' };
      Util.removeLocalStorage('userInfo');
      VueObject.$router.push('Login');
    },
    copy(state, value) {
      let textarea: any = document.createElement("textarea"); 
      // textarea.style = 'display: none;';
      textarea.value = value;

      let currentFocus: any = document.activeElement;
      let toolBoxwrap: any = document.getElementById('content');       
      toolBoxwrap.appendChild(textarea); 
      
      textarea.focus();
      if ( textarea.setSelectionRange ) {
        textarea.setSelectionRange(0, textarea.value.length); 
      } else {
        textarea.select();
      }
        
      let flag: any = false;
      try {
        flag = document.execCommand("copy");
      } catch (eo) {
        flag = false;
      }

      toolBoxwrap.removeChild(textarea); 
      currentFocus.focus();
      console.log( flag );
      if ( flag ) VueObject.$toast('复制成功：'+value);
      else VueObject.$toast('复制失败');
    }
  },
  actions: {
    dataToImg(state, dataURI){
      VueObject.$toast(dataURI, dataURI.length);
			let binary = atob(dataURI.split(',')[1]);
			let type = dataURI.split(',')[0];
			let array = [];
      for(let i = 0; i < binary.length; i++) { array.push( binary.charCodeAt(i) ); }      
      let fileData = new Blob([ new Uint8Array( array ) ], { type });
      let form = new FormData();
      let fileOfBlob = new File([ fileData ], new Date() + '.jpg');
      form.append("file", fileOfBlob);
      return axios.post('/api/upload', form)
    }
  }
})
